package model

import (
    "time"
    "fmt"
    "gougouapi/variables"
    _ "gougouapi/conf"
    "strings"
    "gougouapi/util"
    "strconv"
    "database/sql"
)

const UserIdIncKey = "UserIdIncKey"

type userRegister struct {
    Base        `field:"-" json:"-"`
    UserId      string       `field:"user_id"`
    Phone       string       `field:"phone"`
    Password    string       `field:"password"`
}

func NewUserRegister() *userRegister {
    m := new(userRegister)
    m.Init("user_register")
    return m
}

func (this *userRegister) Register(phone, password string) {
    this.UserId = this.BuildUserId()
    this.Phone = phone
    this.Password = password
    _, err := this.DB.Insert(this)
    fmt.Println(err)
}

func (this *userRegister) GetByPhone(phone string) (m *userRegister, err error) {
    if res, e := this.DB.Where(map[string]interface{}{"phone": phone}).FindOne(); e != nil {
        err = e
    } else if res != nil {
        res.Scan(m)
    }
    return
}

func (this *userRegister) BuildUserId() string {
    userId := ""
    now := time.Now().Unix()
    inc := variables.RedisClient.Incr(UserIdIncKey).Val()
    variables.RedisClient.Expire(UserIdIncKey, time.Second)
    incStr := strings.Replace(fmt.Sprintf("%4d", inc), " ", "0", -1)
    rand := util.Rand(100, 999)
    str := fmt.Sprintf("%d%s%d", now, incStr, rand)
    userIdInt, _ := strconv.ParseInt(str, 10, 64)
    userId = strings.ToUpper(strconv.FormatInt(userIdInt, 32))
    return userId
}


